package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;

/*全局异常处理
 *@author 陈汝森
 */
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class })
@Slf4j
public class GlobalExecptionHandler {
    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String>  execptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        //Duplicate entry 'zhanhao1' for key 'idx_username'
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");//把异常句子分割作为数组
            String msg=split[2]+"已存在";
            return R.error(msg);
        }
        return  R.error("未知错误");

    }
    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String>  execptionHandler(CustomException ex){
        log.error(ex.getMessage());
        //Duplicate entry 'zhanhao1' for key 'idx_username'

        return  R.error(ex.getMessage());

    }

}
